<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :has-before="false">
        <!-- 使用工具栏组件，通过属性通知父组件不消失左侧内容 -->
        <template #after>
          <el-button type="primary" size="small" @click="onAdd({pid:'0',type:1})">新增权限</el-button>
        </template>
      </PageTools>
      <!-- 列表 -->
      <el-table :data="list" :border="true" row-key="id">
        <el-table-column label="名称" prop="name"></el-table-column>
        <el-table-column label="标识" prop="code"></el-table-column>
        <el-table-column label="描述" prop="description"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="text" @click="onAdd({pid:row.id,type:2})">添加</el-button>
            <el-button type="text" @click="onUpdate(row.id)">编辑</el-button>
            <el-button type="text" @click="onDel(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 注册对话框组件 -->
    <add-Perm v-if="showDialog" ref="addPremRef" :visible="showDialog" title="权限管理" @close="showDialog=false"></add-Perm>
  </div>
</template>

<script>
import { delPermission, getPermissionDetail, getPermissionList } from '@/api/permisson'
import { translateToTree } from '@/utils'

import AddPerm from './components/addPerm.vue'
export default {
  name: 'PermissionPage',
  components: {
    AddPerm
  },
  data() {
    return {
      list: [],
      showDialog: false
    }
  },
  created() {
    this.getPermissionList()
  },
  mounted() {

  },
  methods: {
    // 编辑
    async onUpdate(id) {
      // 获取数据回显
      const form = await getPermissionDetail(id)
      this.showDialog = true
      await this.$nextTick()
      // 数据赋值给表单
      this.$refs.addPremRef.form = form
    },
    // 点击删除
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        // 发请求
        await delPermission(id)
        // 提示成功
        this.$message.success('操作成功')
        // 刷新列表
        this.getPermissionList()
      })
    },
    // 点击添加按钮 和 新增权限按钮
    async onAdd(data) {
      this.showDialog = true
      // 对象赋值-标准写法
      /*
      */
      // this.$refs.addPremRef.form.type = data.type
      // this.$refs.addPremRef.form.pid = data.pid
      // 对象赋值，通过Object.assign
      //
      await this.$nextTick()
      Object.assign(this.$refs.addPremRef.form, data)
    },
    // 渲染页面生成列表
    async getPermissionList() {
      // list转成树形结构
      this.list = translateToTree(await getPermissionList(), '0')
      console.log(this.list)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
